package com.neo.push.core.codec;

import com.neo.push.core.MessageType;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * Created by lock on 17-7-11.
 */
public class MessageDecoderHandler extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int readable = byteBuf.readableBytes();
        if(readable<6){
            return;
        }
        byteBuf.markReaderIndex();
        int length = byteBuf.readInt();
        if(length>readable){
            byteBuf.resetReaderIndex();
            return;
        }
        short type = byteBuf.readShort();
        byte[] content = new byte[length-6];
        byteBuf.readBytes(content);
        list.add(MessageType.instance(type).decode(content));
    }
}
